#!/usr/bin/python
# -*- coding: utf-8 -*-
# from flask import g
import math
import sys

sys.path.append("../")
sys.path.append("../../")
from datetime import datetime
from flask import make_response, jsonify, Flask, json
from sqlalchemy import exc, create_engine, select, event

from schema.ComManager import ComManager

from schema.ComPartner import ComPartner
from sqlalchemy.orm import sessionmaker, Query, class_mapper, scoped_session

app = Flask(__name__)
engine = create_engine(
    'mysql+pymysql://root:lx@123...@47.94.141.36:3306/supervisory_spider?charset=utf8',
    encoding='utf-8', echo=True, pool_recycle=1200, pool_size=100)

session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))


# DBSession = sessionmaker(bind=engine,autocommit=True)
# session = DBSession()


@app.teardown_appcontext
def shutdown_session(exception=None):
    session.remove()


@event.listens_for(engine, "engine_connect")
def ping_connection(connection, branch):
    if branch:
        return
    try:
        connection.scalar(select([1]))
    except exc.DBAPIError as err:
        if err.connection_invalidated:
            connection.scalar(select([1]))
        else:
            raise


@app.route('/combine/<id>')
def combine(id):
    res = session.execute('SELECT json from combine_v1 where company_id="{}"'.format(id)).fetchall()
    # res = session.execute('SELECT * from combine_v1 where company_id="{}"'.format(id)).fetchall()
    response = make_response(res[0][0])
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    response.headers['Content-Type'] = 'text/html; charset=utf-8'
    return response


def object_to_dict(obj):
    columns = [column.key for column in class_mapper(obj.__class__).columns]
    get_key_value = lambda c: (c, getattr(obj, c).isoformat()) if isinstance(getattr(obj, c), datetime) else (
    c, getattr(obj, c))
    return dict(map(get_key_value, columns))


@app.route('/manager/<id>/<page>')
def manager(id, page):
    page = int(page)
    if page < 1:
        return ""

    num = int(session.execute('SELECT COUNT(1) FROM com_manager WHERE company_id="{}"'.format(id)).fetchall()[0][0])
    data = session.query(ComManager).filter(ComManager.company_id == id)[(page - 1) * 10:page * 10]
    dic = {
        'num': num,
        'totalPage': math.ceil(int(num) / 10),
        'data': [object_to_dict(i) for i in data]
    }

    response = make_response(json.dumps(dic))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    response.headers['Content-Type'] = 'text/html; charset=utf-8'
    return response


@app.route('/partner/<id>/<page>')
def partner(id, page):
    page = int(page)
    if page < 1:
        return ""
    num = int(session.execute('SELECT COUNT(1) FROM com_partner WHERE company_id="{}"'.format(id)).fetchall()[0][0])
    totalPage = math.ceil(int(num) / 10)
    data = session.query(ComPartner).filter(ComPartner.company_id == id)[(page - 1) * 10:page * 10]

    dic = {
        'num': num,
        'totalPage': totalPage,
        'data': [object_to_dict(i) for i in data]
    }
    response = make_response(json.dumps(dic))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    response.headers['Content-Type'] = 'text/html; charset=utf-8'
    return response


@app.route('/branch/<id>/<page>')
def branch(id, page):
    page = int(page)
    if page < 1:
        return ""
    num = session.execute('SELECT COUNT(1) FROM com_partner WHERE company_id="{}"'.format(id)).fetchone()[0]
    totalPage = math.ceil(int(num) / 10)
    if page > totalPage:
        return ""
    data = session.execute(
        'SELECT * FROM com_partner WHERE company_id="{}" LIMIT {},{}'.format(id, (page - 1) * 10, page * 10)).fetchall()
    perty = []
    for i in data:
        perty.append({"name": i[2], "share_rate": i[3]})
    dic = {
        'num': num,
        'totalPage': totalPage,
        'data': perty
    }
    response = make_response(json.dumps(dic))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'POST'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    response.headers['Content-Type'] = 'text/html; charset=utf-8'
    return response


@app.route('/count/<id>')
def count(id):
    manager = int(session.execute('SELECT COUNT(1) FROM com_manager WHERE company_id="{}"'.format(id)).fetchone()[0])
    partner = int(session.execute('SELECT COUNT(1) FROM com_partner WHERE company_id="{}"'.format(id)).fetchone()[0])

    dic = {
        'manager': manager,
        'partner': partner,
        'branch': 0,
        'inv': 0,
        'combine': 0
    }
    response = make_response(json.dumps(dic))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'POST'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    response.headers['Content-Type'] = 'text/html; charset=utf-8'
    return response


if __name__ == '__main__':

    try:
        app.run(host='0.0.0.0', threaded=True, debug=False, port=8787)
    except Exception as e:
        print(e)
